package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id){
        //缓存穿透
        Shop shop = cacheClient
                .queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //Shop shop = queryWithPassThrough(id);

        //互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        //逻辑过期解决缓存击穿
        //Shop shop = queryWithLogicalExpire(id);

        if(shop==null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    @Override
    //单体服务同一事务
    @Transactional
    public Result update(Shop shop) {
        //获取店铺id
        Long id = shop.getId();
        if(id==null){
            return Result.fail("店铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        // 4.解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }

    //    //Hash版本的
//
//
//    //线程池
//    private ExecutorService CACHE_REBULID_EXECUTOR = Executors.newFixedThreadPool(10);
//
//    public Shop queryWithLogicalExpire(Long id) {
//        //从redis查询商铺缓存
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        //取不了空值
//        Map<Object, Object> shopMap = stringRedisTemplate.opsForHash().entries(key);
//        //没有命中直接返回
//        if(shopMap.size() == 0){
//            return null;
//        }
//        //命中数据则要获取RedisData中的data
//        RedisData redisData = BeanUtil.fillBeanWithMap(shopMap, new RedisData(), false);
//        //返回的是Json字符串,反序列化为Shop类型
//        String data = (String)redisData.getData();
//        // 将 JSON 字符串转换为 Shop 对象
//        Shop shop = JSONUtil.toBean(data, Shop.class);
//        //判断逻辑时间是否过期
//        LocalDateTime expireTime = redisData.getExpireTime();
//        //未过期返回店铺信息
//        if(expireTime.isAfter(LocalDateTime.now())){
//            return shop;
//        }
//
//        //过期则需要缓存重建
//        //获取互斥锁
//        String lockKey = LOCK_SHOP_KEY+id;
//        boolean judge = tryLock(lockKey);
//        //判断是否获取成功
//        if(judge){
//            //成功则开启独立线程
//            CACHE_REBULID_EXECUTOR.submit(()->{
//                try {
//                    //重建缓存
//                    this.saveShopRedis(id,20L);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally {
//                    //释放锁
//                    unLock(lockKey);
//                }
//            });
//        }
//        //失败返回过期店铺信息
//        return shop;
//    }
//
//    public Shop queryWithMutex(Long id) {
//        //从redis查询商铺缓存
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        //取不了空值，如果用了Hash存储，那么缓存保护也要用Hash存储
//        Map<Object, Object> shopMap = stringRedisTemplate.opsForHash().entries(key);
//        //命中数据，不是null也不是""
//        if(shopMap != null && !shopMap.isEmpty()){
//            //命中空字符串
//            if (shopMap.containsKey(CACHE_NULL) && CACHE_NULL_VALUE.equals(shopMap.get(CACHE_NULL))) {
//                return null;
//            }
//            //正常数据，存在直接返回
//            return BeanUtil.fillBeanWithMap(shopMap, new Shop(), false);
//        }
//        //需要实现缓存重建
//        //获取互斥锁
//        String lockKey = LOCK_SHOP_KEY+id;
//        Shop shop = null;
//        try {
//            boolean judge = tryLock(lockKey);
//
//            //判断是否获取成功
//            if(!judge){
//                //失败，则休眠并重试
//                Thread.sleep(200);
//                return queryWithMutex(id);
//            }
//
//            //没有命中根据id查询数据库
//            shop = getById(id);
//            //不存在则报错
//            if(shop == null){
//                //将空值写入redis
//                // 使用特殊字段标记空值
//                stringRedisTemplate.opsForHash().put(key,CACHE_NULL,CACHE_NULL_VALUE);
//                stringRedisTemplate.expire(key,CACHE_NULL_TTL,TimeUnit.MINUTES);
//                return null;
//            }
//            //存在则写入redis
//            Map<String, Object> shopMap2 = BeanUtil.beanToMap(shop, new HashMap<>(),
//                    CopyOptions.create().setIgnoreNullValue(true)
//                            .setFieldValueEditor((fileName, fileValue) -> fileValue==null?null:fileValue.toString())
//            );
//            stringRedisTemplate.opsForHash().putAll(key,shopMap2);
//            stringRedisTemplate.expire(key,CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } finally {
//            //释放锁
//            unLock(lockKey);
//        }
//        //返回
//        return shop;
//    }
//
//    public Shop queryWithPassThrough(Long id) {
//        //从redis查询商铺缓存
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        //取不了空值，如果用了Hash存储，那么缓存保护也要用Hash存储
//        Map<Object, Object> shopMap = stringRedisTemplate.opsForHash().entries(key);
//        //命中数据，不是null也不是""
//        if(shopMap != null && !shopMap.isEmpty()){
//            //命中空字符串
//            if (shopMap.containsKey("empty") && "true".equals(shopMap.get("empty"))) {
//                return null;
//            }
//            //正常数据，存在直接返回
//            return BeanUtil.fillBeanWithMap(shopMap, new Shop(), false);
//        }
//        //没有命中根据id查询数据库
//        Shop shop = getById(id);
//        //不存在则报错
//        if(shop == null){
//            //将空值写入redis
//            // 使用特殊字段标记空值
//            stringRedisTemplate.opsForHash().put(key,"empty","true");
//            stringRedisTemplate.expire(key,CACHE_NULL_TTL,TimeUnit.MINUTES);
//            return null;
//        }
//        //存在则写入redis
//        Map<String, Object> shopMap2 = BeanUtil.beanToMap(shop, new HashMap<>(),
//                CopyOptions.create().setIgnoreNullValue(true)
//                .setFieldValueEditor((fileName, fileValue) -> fileValue==null?null:fileValue.toString())
//        );
//        stringRedisTemplate.opsForHash().putAll(key,shopMap2);
//        stringRedisTemplate.expire(key,CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        //返回
//        return shop;
//    }
//
//    private boolean tryLock(String key){
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1",LOCK_SHOP_TTL,TimeUnit.MINUTES);
//        return BooleanUtil.isTrue(flag);
//    }
//    private void unLock(String key){
//        stringRedisTemplate.delete(key);
//    }
//
//    public void saveShopRedis(Long id ,Long expireSecond ){
//        //查询店铺
//        Shop shop = getById(id);
//
//        //封装逻辑过期时间
//        RedisData redisData = new RedisData();
//        //将shop对象转换为Json字符串
//        String jsonData = JSONUtil.toJsonStr(shop);
//        redisData.setData(jsonData);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));
//
//        //写入redis
//        Map<String, Object> shopMap = BeanUtil.beanToMap(redisData, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true)
//                .setFieldValueEditor((fileName, fileValue) -> fileValue == null ? null : fileValue.toString())
//        );
//        stringRedisTemplate.opsForHash().putAll(CACHE_SHOP_KEY+id,shopMap);
//    }


}
